package ecode

import "errors"

var (
	m               = make(map[int]*BizError)
	ErrUnknownError = RegisterError(90001, "未知错误")
	ErrRequestParam = RegisterError(90002, "请求参数错误")
	ErrDBExecution  = RegisterError(90003, "数据库执行错误")

	// micro ecode

	// reversesh ecode
	ErrDuplicateConfig = RegisterError(92001, "node ip已存在")
	ErrEnablePlugin    = RegisterError(92002, "启用插件失败")

	// Cluster ecode
	ErrClusterNameExists       = RegisterError(93001, "集群名称已存在")
	ErrClusterNotExists        = RegisterError(93002, "集群不存在")
	ErrClusterResourceFetching = RegisterError(93003, "集群资源获取失败")
	ErrCreateResource          = RegisterError(93004, "创建资源失败")
	ErrDeleteResource          = RegisterError(93005, "删除资源失败")

	// prometheus
	ErrPrometheusConnect = RegisterError(94001, "Prometheus连接失败")
	ErrPrometheusQuery   = RegisterError(94002, "Prometheus查询失败")
)

func init() {
	m = make(map[int]*BizError)
}

type BizError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (e *BizError) Error() string {
	return e.Message
}

func RegisterError(code int, msg string) *BizError {
	b := &BizError{
		Code:    code,
		Message: msg,
	}
	m[code] = b
	return b
}

func IsBizError(err error) bool {
	if err == nil {
		return false
	}
	var bizError *BizError
	if errors.As(err, &bizError) {
		return true
	}
	return false
}
